package sum.book.auth.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import sum.book.auth.dto.user.CustomUser;
import sum.book.auth.server.dao.mapper.UserDao;
import sum.book.auth.server.entity.UserDo;
import sum.book.common.core.utils.SimpleConverter;

import java.util.Optional;

@Service
public class CustomUserDetailServiceImpl extends ServiceImpl<UserDao, UserDo> implements UserDetailsService {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<UserDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDo::getUsername, username);

        UserDo userDo = getOne(queryWrapper);

        Optional.ofNullable(userDo).orElseThrow(() -> new UsernameNotFoundException(username + "不存在!!!"));

        return SimpleConverter.convert(userDo, CustomUser.class);
    }

}
